{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "https://mp.weixin.qq.com/s?__biz=MzkxODE3NjExOQ==&mid=2247485351&idx=1&sn=422171afd86fa4292068d31d94b0ea0a&chksm=c1b42fbff6c3a6a93fb4cf2f6666839e8810d3b30619af87cd977cb755039e4ded6ee130e749&scene=178&cur_album_id=3354758663365918722#rd"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 导入需要使用的库\n",
    "import akshare as ak\n",
    "import pandas as pd\n",
    "import numpy as np\n",
    "# 关闭警告信息\n",
    "import warnings\n",
    "warnings.filterwarnings('ignore')\n",
    "\n",
    "# 设置取数日期范围\n",
    "start_date = '20140101'\n",
    "end_date = '20231229'\n",
    "# 获取基准指数的收盘价数据\n",
    "benchmark = \"000300\"\n",
    "bars = ak.stock_zh_index_hist_csindex(symbol=benchmark, start_date=start_date, end_date=end_date)\n",
    "# 将日期设置为datetime格式\n",
    "bars['日期'] = pd.to_datetime(bars['日期'])\n",
    "prices_df = pd.DataFrame(index=bars['日期'])\n",
    "prices_df[f'{benchmark}'] = bars.set_index('日期')['收盘']\n",
    "\n",
    "# 获取股票的收盘价数据\n",
    "stock = \"600519\"\n",
    "bars = ak.stock_zh_a_hist(symbol=stock, period=\"daily\", start_date=start_date, end_date=end_date, adjust=\"qfq\")\n",
    "# 将日期设置为datetime格式\n",
    "bars['日期'] = pd.to_datetime(bars['日期'])\n",
    "prices_df[f'{stock}'] = bars.set_index('日期')['收盘']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 计算信息比率（Information Ratio）\n",
    "annual_periods = 244  # 年化期数，一年约244个交易日\n",
    "# 计算基准和标的股票的日收益率\n",
    "returns = prices_df.pct_change().fillna(0)\n",
    "# 计算日超额收益率 = 标的股票日收益率 - 基准日收益率\n",
    "returns_diff = returns[f'{stock}'] - returns[f'{benchmark}']\n",
    "# 计算信息比率（Information Ratio） = 每日超额收益的均值 / 每日超额收益的标准差\n",
    "information_ratio = returns_diff.mean() / returns_diff.std() * np.sqrt(annual_periods)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "-0.33811859056726173"
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "information_ratio"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "4broker",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.4"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
